<?php

namespace app\common\model\worker;

use app\common\model\AdminModel;
use app\common\model\BaseModel;
use app\common\model\node\NodeModel;
use app\common\model\offer\GoodsModel;
use helper\Arr;

use DateTime;
class CustomerModel extends BaseModel
{
    protected $table = 'customer';

    public function customerGoodsData(){
        return $this->hasMany('app\common\model\worker\CustomerGoodsDataModel','customer_id','id');//->hidden(['id,customer_id']);
    }
    public function customerRectifyData(){
        return $this->hasMany('app\common\model\worker\CustomerRectifyDataModel','customer_id','id');
    }


    public function _formatList($list)
    {

        // $offerList = Arr::group($offerList,'customer_id');
        $good_arr_info = GoodsModel::where('pid', 0)->field('id,goods_name')->select()->toArray();
        $good_arr = GoodsModel::where('pid', 0)->field('id,goods_name')->column('id');
//        $goods = GoodsModel::where('pid', 0)->column('goods_name');
        $goods_str = implode(',',$good_arr);

        $total_expect_payment = 0;
        foreach ($list as $k=>&$v){

            $goods_arr_new = [];
            $total_amount = 0;
             $customerGoodsData =    json_decode($v['customerGoodsData']);
             
            if(empty($customerGoodsData )){
            
                unset($list[$k]);
                continue;
            }
            $total_expect_payment += $v['expect_payment'];
     
            //产品预算金额
            foreach($v['customerGoodsData'] as $kk => &$vv){

                //商品预算金额，完成预算 和申请预算或申请量房时填写的客户预算没有关系，这个是客户代表完成预算的折后价
                if($vv['budget_id'] && $vv['budget_status'] == 1){

                    $vv['budget_amount'] = CustomerBudgetDetailModel::where('id',$vv['budget_detail_id'])->value('final_price');
                }else{

                    $vv['budget_amount'] = 0;
                }

                //签完合同之价格后显示合同
                if($vv['contract_id']){

                    $vv['budget_amount'] = CustomerContractModel::where('id',$vv['contract_id'])->value('final_price');
                }

                $total_amount += $vv['budget_amount'];



                $v['customerGoodsData'][$kk]['behalf_name'] = '';
                //客户代表 预算完成 申请预算后，没有审核，不带名字，是没有申请预算 申请预算后，审核通过，带名字，待预算
                if($vv['budget_id'] && $vv['budget_status'] >= 0){
                    $admin_id = CustomerBudgetModel::where('id',$vv['budget_id'])->value('admin_id');
                    $v['customerGoodsData'][$kk]['behalf_name'] = AdminModel::where('id',$admin_id)->value('nickname');
                }
                $v['customerGoodsData'][$kk]['designer_name'] = '';
                //设计师 量房完成
                if($vv['ruler_id'] && $vv['design_status'] >= 0 ){
                    $admin_id = CustomerRulerModel::where('id',$vv['ruler_id'])->value('admin_id');

                    $v['customerGoodsData'][$kk]['designer_name'] = AdminModel::where('id',$admin_id)->value('nickname');
                }



                $goods_arr_new[] = $vv['goods_id'];




            }
//            var_dump($goods_arr_new);exit;
            foreach ($good_arr_info as &$gvv){
                $gvv['class'] = 'black';
                if(in_array($gvv['id'],$goods_arr_new)){
                    $gvv['class'] = 'red';
                }
            }



//            var_dump($good_arr_info);exit;
            $v['goods_show'] = $good_arr_info;
            //var_dump($v['customerGoodsData']);exit;
            //预算金额
            $list[$k]['budget_amount'] = $total_amount ?? 0;//客户金额

            //推荐人信息
            $list[$k]['recommend_name'] = '';
            $list[$k]['recommend_mobile'] = '';
            $list[$k]['recommend_compay'] = '';
            $recommendInfo = RecommendModel::where('id',$v['recommend_id'])->field('id,recommend_compay,recommend_name,recommend_mobile')->find();
            if($v['recommend_id'] && $recommendInfo){

                $list[$k]['recommend_name'] = $recommendInfo['recommend_name'] ?? '';
                $list[$k]['recommend_mobile'] = $recommendInfo['recommend_mobile'] ?? '';
                $list[$k]['recommend_compay'] = $recommendInfo['recommend_compay'] ?? '';
            }

            //客户所属人
            $admin_id = CustomerAuthModel::where('customer_id',$v['id'])->where('role','create')->value('admin_id');
            $list[$k]['create_man_info'] = AdminModel::where('id',$admin_id)->field('id,mobile,nickname')->find()->toArray();
            //跟进信息
            $customerFollowLogInfo = CustomerFollowLogModel::where('customer_id',$v['id'])->order('id','desc')->find();
            $day_diff = '';
            if($customerFollowLogInfo){
                $date1 = new DateTime("now");

                $date2 = new DateTime($customerFollowLogInfo['create_time']);

                $interval = $date1->diff($date2);
                $day_diff = $interval->days;

            }else{
                $customerFollowLogInfo = CustomerModel::where('id',$v['id'])->find();
                $date1 = new DateTime("now");

                $date2 = new DateTime($customerFollowLogInfo['create_time']);

                $interval = $date1->diff($date2);
                $day_diff = $interval->days;
            }
            $v['day_diff'] = $day_diff;
            $list[$k]['follow_info'] =
                [
                    'follow_content' => $customerFollowLogInfo['content'] ?? '',
                    'follow_day'     => $day_diff ?? '',
                ];
        }
        return [$list,$total_expect_payment];
    }

    public function addCustomerGoodsData($data,$admin_id){
        $goods_ids = [];
        foreach ($data['customer_goods_names'] as $v){
            $goodsInfo = GoodsModel::where('goods_name',$v)->where('pid',0)->find();
            $goods_ids[] = $goodsInfo['id'];


        }

        $customer_goods_data = [];
        foreach ($data['customer_goods_names'] as $k =>$v){
            $customer_goods_data[$k]['goods_id'] = $goods_ids[$k];
            $customer_goods_data[$k]['customer_id'] = $data['customer_id'];
            $customer_goods_data[$k]['goods_name'] = $v;
            $customer_goods_data[$k]['action_admin_id'] = $admin_id;//操作人id
        }

        $result = CustomerGoodsDataModel::insertAll($customer_goods_data);
        if(!$result){
            return false;
        }

      return true;
    }

    /**
     * 添加客户
     * @param $data
     * @throws \Exception
     */
    public function add($data,$adminId)
    {



//        if(isset($data['customer_goods_names'])){
//            $data['customer_goods_names'] = implode(',',$data['customer_goods_names']);
//        }

        //unset($data['action_admin_id']);
        $info = self::create($data);
     
        $authData = [
            'customer_id'=>$info['id'],
            'role'=>'create',//创建者
            'admin_id'=>$adminId,
            'action_admin_id'=>$adminId
        ];

        CustomerAuthModel::create($authData);

        return $info;

    }

    /**
     * 编辑客户
     * @param $data
     * @throws \Exception
     */
    public function edit($data)
    {

//        $customer_goods_names = $this->where('id',$data['id'])->column('customer_goods_names');
//        $new_goods_names = [];
//        foreach($data['customer_goods_names'] as $v){
//            if(!in_array($v,$customer_goods_names)){
//                $new_goods_names[] = $v;
//                $goodsInfo = GoodsModel::where('goods_name',$v)->where('pid',0)->find();
//                $goods_ids[] = $goodsInfo['id'];
//            }
//        }
//        unset($data['customer_goods_names']);
//        if(!empty($new_goods_names)){
//            $customer_goods_data = [];
//            foreach ($new_goods_names as $k =>$v){
//                $customer_goods_data[$k]['goods_id'] = $goods_ids[$k];
//                $customer_goods_data[$k]['customer_id'] = $data['id'];
//                $customer_goods_data[$k]['goods_name'] = $v;
//            }
//             $result = CustomerGoodsDataModel::insertAll($customer_goods_data);
//            if(!$result){
//                return false;
//            }
//        }
        unset($data['customer_goods_names']);
        return self::update($data);
    }

    public function getInfo($map){
        $info = $this->where($map)->find();
        $authModel = new CustomerAuthModel();
        $authList = $authModel->where('customer_id','=',$info['id'])->column('role','admin_id');
        $info['auth_list'] = $authList;
        $info['admin_id'] = $authModel->where('customer_id','=',$info['id'])->where('role','create')->value('admin_id');
        $info['customer_imgs'] = empty($info['customer_imgs'])?[]:json_decode($info['customer_imgs'],true);
        $info['customer_file'] = empty($info['customer_file'])?[]:json_decode($info['customer_file'],true);
        return $info;
    }

    /**
     * 删除客户信息
     * @param $id
     */
    public function del($id){
        //todo 已有订单的客户不允许删除
        $info = $this->where('id',$id)->find();
        if($info['order_total_amount']>0) exception('客户还有未支付款项，禁止删除');
        if($info['payment_amount']>0) exception('客户已有付款，禁止删除');
        TaskModel::where('customer_id',$id)->delete();
        CustomerAuthModel::where('customer_id',$id)->delete();
        OfferModel::where('customer_id',$id)->delete();
        $this->where('id',$id)->delete();
        return true;
    }


}
